$(function () {
//    readOnly($("#xsht_lj_id"));
    $('#xsht_sl').slsjzdcombobox("sl");
    xshtContent($("#xsht_xy").val());
    if($("#xsht_htms").val()=='xsms'){//线上单据
        $("#lj_display").css("display","none");
    }else{
        if ($("#xsht_lj_id").length > 0) {
            $("#xsht_lj_id").ljcombobox($("#xsht_zggsId").val(), 2, {
                onSelect: function (record) {
                    if ($("#xsht_scms").combobox('getValue') == 'ljsc') {

                        $.post($.webPath() + '/organ/ljwh/ljinfosxy', {'ljId': record.id}, function (data) {
                            var xydata = [];
                            $(data).each(function (i, item) {
                                if (item.lx == 'xy') {    //下游
                                    xydata.push(item);
                                }
                            })

                            if ($("[name='xsht.id']").val() == '') {
                                if (xydata && xydata[0])
                                    $("#xsht_hzf_id").loadLocalRegion(xydata, xydata[0].id);
                            } else {
                                if (xydata && xydata[0])
                                    $("#xsht_hzf_id").loadLocalRegion(xydata, '');
                            }
                        })

                        $("#xsht_jsyj_id").combobox('setValue', record.jsfs_id);
                        $("#xsht_hkqx").val(record.hkq);

                        $("#xsht_xslx_mc").val("库存销售");
                        $("[name='xsht.xslx']").val('kcxs');

                    }
                },
                onLoadSuccess: function () {
                    if ($("#xsht_scms").combobox('getValue') != 'ljsc') {
                        $("#xsht_lj_id").combobox('readonly', true);
                    }
                }
            });
        }
    }




//    $("[name='xsht.xy.id']").combogrid({
//        panelWidth: 630,
//        idField: 'id',
//        textField: 'xyhm',
//        fitColumns: true,
//        pagination: true,//是否分页
//        rownumbers: true,//序号
//        collapsible: false,//是否可折叠的
//        fit: true,//自动大小
//        pageSize: 10,//每页显示的记录条数，默认为10
//        url: $.webPath() + '/jhgl/xygl/simpleXsXyList',
//        columns: [
//            [
//                {field: 'xyhm', title: '协议编号', width: 100},
//                {field: 'kh_qc', title: '客户', width: 80},
//                {field: 'nxyl', title: '年协议量', formatter: function (value) {
//                    var sl = formatSlForHtml(value, ",");
//                    return sl;
//                }, width: 50},
//                {field: 'yxyl', title: '月协议量',
//                    formatter: function (value) {
//                        var sl = formatSlForHtml(value, ",");
//                        return sl;
//                    }, width: 50},
//                {field: 'zdsj', title: '制单时间', width: 80}
//            ]
//        ],
//        onChange: function (newValue, oldValue) {
//            var g = $(this).combogrid('grid');
//            var row = g.datagrid('getSelected');
//            initXsht(row);
//        }
//    });

    //合作方加载
    $("#xsht_hzf_id").combobox({
        valueField: 'id',
        textField: 'jc',
        onChange: function () {
            //加载客户对应的工程
            var xsht_hzf = $("#xsht_hzf_id").combobox('getValue');
            $("#xsht_gc_id").gccombobox(xsht_hzf);
        },
        onLoadSuccess: function () {
            //加载客户对应的工程
            var xsht_hzf = $("#xsht_hzf_id").combobox('getValue');
            $("#xsht_gc_id").gccombobox(xsht_hzf);
        }
    });
    //采购公司加载
    //合同性质
    $("[name='xsht.htxz.id']").sjzdcombobox('htxz');
    //付款方式
    $("[name='xsht.fkfs.id']").sjzdcombobox('fkfs');
    //计算依据
    $("[name='xsht.jsyj.id']").sjzdcombobox('khjsfs');
    //发运责任
    $("[name='xsht.fhzr.id']").sjzdcombobox('fyzr', {
        onLoadSuccess: function () {
            $("[name='xsht.fhzr.id']").val(42)
        }
    });
    //销售费用
    $("[name='xsht.xsfy.id']").sjzdcombobox('xsfy');

    var xsht_hzf = $("#xsht_hzf_id").combobox('getValue');
    $("#xsht_gc_id").gccombobox(xsht_hzf);

    $("#xsht-uploadify").upload('xsht-fileQueue', {
        onUploadSuccess: function (file, data, response) {
            var obj = eval('(' + data + ')');
            $("#xsht-fileQueue .data").remove();
            $("#xsht-fileQueue .uploadify-progress").fadeOut(500, function () {
                $(this).remove();
            });
            $("#" + file.id).append("<input type='hidden' id='xsht-file" + obj.fileId + "' name='xsht.fjList.id' value='" + obj.fileId + "'/>");
            $("#" + file.id + " .cancel a").bind('click', function () {
                $(this).attr('href', 'javascript:void(0)');
                deleteXshtFile(obj.fileId, file.id);
            });
        }
    });


    //新增合同明细
    $("#xshtgl_xshtmx_toolbar [name='xzxshtmx']").click(function () {
        searchcodewindow(xshtmx_searchWindowOKbtnHandler);
    });
    //删除合同明细
    $("#xshtgl_xshtmx_toolbar [name='scxshtmx']").click(function () {
        var rows = $("#xsht_mx").edatagrid('getChecked');
        if (rows) {
            $.messager.confirm('提示', '是否确定删除合同明细?', function (r) {
                if (r) {
                    $.each(rows, function (i, val) {
                        var index = $("#xsht_mx").edatagrid('getRowIndex', val);
                        $("#xsht_mx").edatagrid('deleteRow', index);
                    });
                    countSumXs();
                }
            });
        }
        $("#xsht_mx").edatagrid('resize');
    });


    $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'cd'}, function (cddata) {
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
            xsmxGrid(cddata, data);
        })
    });


    // 加载合同模板
    if ($("[name='xsht.id']").val()) {
        $("[name='xsht_htmb']").htmbcombobox(false, $("[name='htdyId']").val(), {
            onChange: function (oldValue, newValue) {
                // 加载合同文本
                $.ajax({
                    type: "POST",
                    url: $.webPath() + "/htdygl/htwb/htwbDetail",
                    dataType: "html",
                    data: {htmbId: oldValue, htdyId: $("[name='htdyId']").val(), htId: $("[name='xsht.id']").val()},
                    beforeSend: function () {
//                        $.messager.progress();
                    },
                    success: function (data) {
//                        $.messager.progress("close");
                        $('#htwb_xsht_id').html(data);
                        if (data.statusCode == 300) {
                        }
                        if (data.statusCode == 200) {
                        }
                    }
                });
            }
        });
        // 如果已经有了文本加载文本
        $.ajax({
            type: "POST",
            url: $.webPath() + "/htdygl/htwb/htwbDetail",
            dataType: "html",
            data: {htdyId: $("[name='htdyId']").val(), htId: $("[name='xsht.id']").val()},
            beforeSend: function () {
//                $.messager.progress();
            },
            success: function (data) {
//                $.messager.progress("close");
                $('#htwb_xsht_id').html(data);
                if (data.statusCode == 300) {
                }
                if (data.statusCode == 200) {
                }
            }
        });
    }
});

function deleteXshtFile(fileId, id) {
    $.messager.confirm('确认', '是否确认删除此附件', function (r) {
        if (r) {
            $.post($.webPath() + '/base/fj/deleteFj', {'fjId': fileId}, function (data) {
                var obj = eval('(' + data + ')');
                if (obj.statusCode == '200') {
                    $("#xsht-file" + fileId).remove();
                    $("#" + id).fadeOut(500, function () {
                        $(this).remove();
                    });
                }
            });
        }
    })
}

//查询物资代码确定按钮回调函数
function xshtmx_searchWindowOKbtnHandler(data) {
    var rowdatas = $.map(data, function (n, i) {
        return {
            'wzgg.id': n.id,
            'wzgg.code': n.code,
            'wzgg.name': n.name,
            'wzgg.cz': n.cz,
            'wzgg.ggxh': n.ggxh,
            'wzgg.dw': n.dw,
            'cd.id': null,
            'ck': '',
            'jzfs.id': null,
            'bz': '',
            'sbsl': 0,
            'hsj': 0,
            'bhsj': 0,
            'hsje': 0
        };
    });
    $.each(rowdatas, function () {
        $("#xsht_mx").edatagrid('appendRow', this);
    });
    //xshtmx_countSum();
}

function xsmxGrid(cdOptions, fsOptions) {
    $("#xsht_mx").edatagrid({
        url: $.webPath() + '/htgl/xshtgl/xshtgl_htmx?xshtId=' + $("[name='xsht.id']").val() || '',
        fitColumns: true,
        singleSelect: true,
        fit: true,
        checkbox: true,
        checkOnSelect: false,
        selectOnCheck: false,
        showFooter: true,
        rownumbers: true,
        //showFooter: true,
        toolbar: "#xshtgl_xshtmx_toolbar",
        columns: [
            [
                {field: 'checked', checkbox: true},
                {field: 'wzgg.code', title: '物资编码', width: 50},
                {field: 'wzgg.name', title: '物资名称', width: 40},
                {field: 'wzgg.ggxh', title: '规格型号', width: 40},
                {field: 'wzgg.cz', title: '材质', width: 40},
                {field: 'wzgg.dw', title: '单位', width: 20},
                {field: 'cd.z', title: '产地', width: 40},
                {field: 'sbjs', title: '件数', width: 40},
//                    editor: {type: 'combobox', options: {
//                    data: cdOptions,
//                    valueField: 'id',
//                    textField: 'z',
//                    multiple: false,
//                    panelHeight: '150'
//                }
//                },
//                    formatter: function (value) {
//                    for (var i = 0; i < cdOptions.length; i++) {
//                        if (cdOptions[i].id == value) return cdOptions[i].z;
//                    }
//                    return value;
//                }, },
                {field: 'sbsl',
//                    editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}},
                    title: '重量',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    },
                    width: 70},
                {field: 'jzfs.id', editor: {type: 'combobox', options: {
                    data: fsOptions,
                    valueField: 'id',
                    textField: 'z',
                    multiple: false,
                    panelHeight: '55'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].z;
                    }
                    return value;
                }, title: '记重方式', width: 30},
                {field: 'hsj', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '含税单价(元)',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 70},
                {field: 'bhsj', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '不含税单价(元)',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 70},
                {field: 'hsje', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '含税总金额(元)',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 80}
            ]
        ],
        onSelect: function (rowIndex, rowData) {
            //获取每个单元格
            $("#xsht_mx").edatagrid('editRow', rowIndex);
            var editors = $("#xsht_mx").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;

            var bhsjEditor = editors[2];
            var hsjEditor = editors[1];
            var hsjeEditor = editors[3];
            hsjEditor.target.unbind('blur').bind('blur', function () {
                $(hsjEditor.target).numberbox('setValue', $(hsjEditor.target).val());
                var bhsj = formatMoneyFourWei(tax.getNotIncludingTaxPrice($(hsjEditor.target).numberbox('getValue'), $("#xsht_sl").combobox('getValue')));
                if (!$(bhsjEditor.target).numberbox('getValue'))
                    $(bhsjEditor.target).numberbox('setValue', bhsj);
                else if (Math.abs($(bhsjEditor.target).numberbox('getValue') - bhsj) >= 0.01) {
                    $(bhsjEditor.target).numberbox('setValue', bhsj);
                }
                $(hsjeEditor.target).numberbox('setValue', formatMoney($(hsjEditor.target).numberbox('getValue') * rowData.sbsl));
                countXshtSum(rowIndex, rowData.sbsl, $(hsjEditor.target).numberbox('getValue'));

            });
            bhsjEditor.target.unbind('blur').bind('blur', function () {
                $(bhsjEditor.target).numberbox('setValue', $(bhsjEditor.target).val());
                var hsj = formatMoneyFourWei(tax.getIncludingTaxPrice($(bhsjEditor.target).numberbox('getValue'), $("#xsht_sl").combobox('getValue')));
                if (!$(hsjEditor.target).numberbox('getValue'))
                    $(hsjEditor.target).numberbox('setValue', hsj);
                else if (Math.abs($(hsjEditor.target).numberbox('getValue') - hsj) >= 0.01) {
                    $(hsjEditor.target).numberbox('setValue', hsj);
                }
                $(hsjeEditor.target).numberbox('setValue', formatMoney($(hsjEditor.target).numberbox('getValue') * rowData.sbsl));
                countXshtSum(rowIndex, rowData.sbsl, $(hsjEditor.target).numberbox('getValue'));

            });
        }
    });
}


//function initXsht(r) {
//
//
//    if (r.fkfs_id)
//        $("#xsht_fkfs_id").combobox('setValue', r.fkfs_id);
//    if (r.jhfs)
//        $("#xsht_jhfs").val(r.jhfs);
//
//    if (r.hkqx)
//        $("#xsht_hkqx").numberbox('setValue', r.hkqx);
//    if (r.hkjsfs_id)
//        $("#xsht_jsyj_id").combobox('setValue', r.hkjsfs_id);
//
//    $("#xsht_xslx_mc").val("库存销售");
//    $("[name='xsht.xslx']").val('kcxs');
//
//    if (r.zbcg) {
//        if (r.zbcg == "是") {
//            $("#xsht_zbcg").attr('checked', 'true');
//        } else {
//            $("#xsht_zbcg").removeAttr("checked");
//        }
//    }
//
//    if (r.lj_id) {
//        var li = {id: r.lj_id, mc: r.lj_mc}
//        $("#xsht_lj_id").combobox('loadData', [li]);
//        $("#xsht_lj_id").combobox('setValue', r.lj_id);
//
//
//        $.post($.webPath() + '/organ/ljwh/ljinfosxy', {'ljId': r.lj_id}, function (data) {
//            var xydata = [];
//            $(data).each(function (i, item) {
//                if (item.lx == 'xy') {    //下游
//                    xydata.push(item);
//                }
//            })
//
//            $("#xsht_hzf_id").loadLocalRegion(xydata, r.kh_id);
//        })
//    } else {
//        $("#xsht_lj_id").combobox('loadData', []);
//        $("#xsht_lj_id").combobox('clear');
//    }
//
////    readOnly($("#xsht_lj_id"));
//    $("#xsht_lj_id").combobox('readonly', true);
//}

function xshtContent(kxg) {
    if (kxg) {
        $("#xsht_zbcg").unbind('click').bind('click', function () {
            return false;
        });
    } else {
        $("#xsht_zbcg").unbind('click').bind('click', function () {
            if ($(this).attr("checked") != undefined && $(this).attr("checked") == "checked") {
                //TO-DO 赋值公司本部
                $("#xsht_wlfgs_jc").val("积微物联");
                $("[name='xsht.wlfgs.id']").val(1);
            } else {
                $("#xsht_wlfgs_jc").val($("#xsht_sbgs_jc").val());
                $("[name='xsht.wlfgs.id']").val($("#xsht_sbgs_id").val());
            }
        });
    }

    if ($("[name='xsht.lj.id']").val()) {
        $.post($.webPath() + '/organ/ljwh/ljinfosxy', {'ljId': $("[name='xsht.lj.id']").val()}, function (data) {
            var xydata = [];
            $(data).each(function (i, item) {
                if (item.lx == 'xy') {    //下游
                    xydata.push(item);
                }
            })

            $("#xsht_hzf_id").loadLocalRegion(xydata, '');
        });
    }

}


//计算计划总量
function countXshtSum(index, countSbsl, counthsj) {
    var sumsbsl = 0;
    var sumhsj = 0;
    var sumhsje = 0;
    var data = $("#xsht_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]['sbsl']);
        var hsj = parseFloat(data.rows[i]['hsj']);
        sbsl = isNaN(sbsl) ? 0 : sbsl;
        hsj = isNaN(hsj) ? 0 : hsj;
        if (i == index) {
            sbsl = parseFloat(countSbsl);
            hsj = parseFloat(counthsj);
        }
        sumsbsl += sbsl;
        sumhsj += hsj;
        sumhsje += hsj * sbsl;
    }
    addFooter(sumsbsl, sumhsj, sumhsje);
}

//计算计划总量
function countSumXs() {
    var sumsbsl = 0;
    var sumhsj = 0;
    var sumhsje = 0;
    var data = $("#xsht_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]['sbsl']);
        var hsj = parseFloat(data.rows[i]['hsj']);
        sbsl = isNaN(sbsl) ? 0 : sbsl;
        hsj = isNaN(hsj) ? 0 : hsj;
        sumsbsl += sbsl;
        sumhsj += hsj;
        sumhsje += sbsl * hsj;
    }
    addFooter(sumsbsl, sumhsj, sumhsje);
}

function addFooter(sumsbsl, sumhsj, sumhsje) {
    var sumbhsj = 0;
    if ($("#xsht_sl").length > 0) {
        sumbhsj = tax.getNotIncludingTaxPrice(sumhsj, $("#xsht_sl").combobox('getValue'));
    }
    var footer = [
        {"cd.id": "合计", "sbsl": formatMoneyFourWei(sumsbsl), "bhsj": formatMoneyFourWei(sumbhsj), "hsj": formatMoneyFourWei(sumhsj), "hsje": formatMoney(sumhsje)}
    ];
    if (footer != null)
        $("#xsht_mx").edatagrid('reloadFooter', footer);
}
